package org.wzy.xmlg_backend.controller;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wzy.xmlg_backend.entity.Emp;
import org.wzy.xmlg_backend.entity.Result;
import org.wzy.xmlg_backend.service.IEmpService;
import org.wzy.xmlg_backend.service.IDeptService;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@Tag(name = "EmpController", description = "员工表")
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private IEmpService empService;

    @Autowired
    private IDeptService deptService;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.access-path}")
    private String accessPath;

    @PostMapping("/upload")
    @Operation(summary = "图片上传")
    @CrossOrigin(origins = "*")
    public Result<String> uploadImage(@RequestParam("image") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.fail("上传文件不能为空");
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;

            // 创建目标文件
            Path targetLocation = Paths.get(uploadDir).resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件名（不含路径前缀）
            String fullAccessPath = accessPath + fileName;
            return Result.success(fullAccessPath);

        } catch (Exception e) {
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询员工")
    public Result<Page<Emp>> pageEmps(
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "5") Integer size,
            @Parameter(description = "员工姓名") @RequestParam(required = false) String name,
            @Parameter(description = "性别") @RequestParam(required = false) String gender,
            @Parameter(description = "开始时间") @RequestParam(required = false) String beginTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {

        Page<Emp> page = new Page<>(current, size);

        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(Emp::getName, name);
        }

        if (StringUtils.isNotBlank(gender)) {
            queryWrapper.eq(Emp::getGender, gender);
        }

        if (StringUtils.isNotBlank(beginTime)) {
            queryWrapper.ge(Emp::getEntrydate, beginTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            queryWrapper.le(Emp::getEntrydate, endTime);
        }

        queryWrapper.orderByDesc(Emp::getUpdateTime);

        Page<Emp> result = empService.page(page, queryWrapper);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<Emp> getEmpById(@PathVariable Integer id) {
        Emp emp = empService.getById(id);
        if (emp != null) {
            // 确保返回完整图片路径
            if (StringUtils.isNotBlank(emp.getImage()) && !emp.getImage().startsWith("http")) {
                emp.setImage(accessPath + emp.getImage());
            }
            return Result.success(emp);
        } else {
            return Result.fail("员工不存在");
        }
    }


    @PostMapping
    @Operation(summary = "创建员工")
    public Result<Emp> createEmp(@RequestBody Emp emp) {
        // 验证部门是否存在
        if (emp.getDeptId() != null && deptService.getById(emp.getDeptId()) == null) {
            return Result.fail("部门不存在");
        }

        // 处理图片路径
        if (StringUtils.isNotBlank(emp.getImage())) {
            // 如果是新上传的文件名，拼接完整路径
            if (!emp.getImage().startsWith(accessPath)) {
                String accessUrl = accessPath + emp.getImage();
                emp.setImage(accessUrl);
            }
        }

        // 设置默认密码
        if (emp.getPassword() == null || emp.getPassword().isEmpty()) {
            emp.setPassword("123456");
        }

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        emp.setCreateTime(now);
        emp.setUpdateTime(now);

        boolean success = empService.save(emp);
        if (success) {
            return Result.success(emp);
        } else {
            return Result.fail("创建员工失败");
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新员工")
    public Result<Emp> updateEmp(@PathVariable Integer id, @RequestBody Emp emp) {
        Emp existingEmp = empService.getById(id);
        if (existingEmp == null) {
            return Result.fail("员工不存在");
        }

        // 验证部门是否存在
        if (emp.getDeptId() != null && deptService.getById(emp.getDeptId()) == null) {
            return Result.fail("部门不存在");
        }

        emp.setId(id);
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(existingEmp.getCreateTime());

        // 处理图片路径
        if (StringUtils.isNotBlank(emp.getImage())) {
            // 如果是新上传的文件名，拼接完整路径
            if (!emp.getImage().startsWith(accessPath)) {
                String accessUrl = accessPath + emp.getImage();
                emp.setImage(accessUrl);
            }
        } else {
            // 保留原有图片
            emp.setImage(existingEmp.getImage());
        }

        // 处理密码
        if (emp.getPassword() == null || emp.getPassword().isEmpty()) {
            emp.setPassword(existingEmp.getPassword());
        }

        boolean success = empService.updateById(emp);
        if (success) {
            return Result.success(emp);
        } else {
            return Result.fail("更新员工失败");
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除员工", description = "根据ID删除员工")
    public Result<Void> deleteEmp(@PathVariable Long id) {
        boolean exists = empService.getById(id) != null;
        if (!exists) {
            return Result.fail("员工不存在");
        }

        boolean success = empService.removeById(id);
        if (success) {
            return Result.success();
        } else {
            return Result.fail("删除员工失败");
        }
    }

    @GetMapping("/dept/{deptId}")
    @Operation(summary = "根据部门ID查询员工列表")
    public Result<List<Emp>> getEmpsByDeptId(@PathVariable Integer deptId) {
        if (deptService.getById(deptId) == null) {
            return Result.fail("部门不存在");
        }

        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getDeptId, deptId);

        List<Emp> empList = empService.list(queryWrapper);
        // 确保返回完整图片路径
        empList.forEach(emp -> {
            if (StringUtils.isNotBlank(emp.getImage()) && !emp.getImage().startsWith(accessPath)) {
                emp.setImage(accessPath + emp.getImage());
            }
        });
        return Result.success(empList);
    }

    @PostMapping("/import")
    @Operation(summary = "导入员工数据")
    public Result<String> importEmp(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            List<Emp> empList = EasyExcel.read(inputStream)
                    .head(Emp.class)
                    .sheet()
                    .doReadSync();

            // 处理导入数据（示例逻辑）
            for (Emp emp : empList) {
                // 设置默认密码
                if (emp.getPassword() == null) {
                    emp.setPassword("123456");
                }
                // 设置时间
                LocalDateTime now = LocalDateTime.now();
                emp.setCreateTime(now);
                emp.setUpdateTime(now);
            }

            empService.saveBatch(empList);
            return Result.success("导入成功");
        } catch (Exception e) {
            return Result.fail("导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出员工数据")
    public void exportEmp(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=employees.xlsx");

            List<Emp> empList = empService.list();

            EasyExcel.write(response.getOutputStream(), Emp.class)
                    .sheet("员工数据")
                    .doWrite(empList);
        } catch (IOException e) {
            throw new RuntimeException("导出失败", e);
        }
    }

    @GetMapping("/job/{job}")
    @Operation(summary = "根据职位查询员工列表")
    public Result<List<Emp>> getEmpsByJob(@PathVariable Byte job) {
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getJob, job);

        List<Emp> empList = empService.list(queryWrapper);
        // 确保返回完整图片路径
        empList.forEach(emp -> {
            if (StringUtils.isNotBlank(emp.getImage()) && !emp.getImage().startsWith(accessPath)) {
                emp.setImage(accessPath + emp.getImage());
            }
        });
        return Result.success(empList);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除员工")
    public Result<Void> deleteEmpsBatch(@RequestBody List<Long> ids) {
        boolean success = empService.removeByIds(ids);
        if (success) {
            return Result.success();
        } else {
            return Result.fail("批量删除员工失败");
        }
    }
}